//index.js
//获取应用实例
const app = getApp()
var common = require('../../utils/common.js');
Page({
  data: {
    item: [],
    linkAppid: 'wx13e41a437b8a1d2e',
    link:'',
    titletxt: '',
    title: '商品详细',
    customerinfo:'jdd180605',
    favimg: {
      imgUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5.png',
      curUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5hover.png',
    },
    path: '',
    isIphoneX: false,
    isdetail: false,
    statusBarHeight: app.globalData.statusBarHeight,
    sharetc: false,
    sharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc2.png',
    sharepic2: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc.png',
    shareData: [],
    sharereadytc: false,
    formId: '',
    sharepictc: false,
    shareimg: '',
    detailedtc: false,
    countDownHour: '72',
    countDownMinute: '00',
    countDownSecond: '00',
    totalSecond: 259200,
    inviteNum: 0,
    schedule:false,
    percent: 0,
    friends: [],
    playvideo: false,
    fromapp: false,
    shareEnable: false,
    logined: false,
    actionSheetHidden: true,
    fromOrdinary: false,
    fromShopkeeper: false,
    isShopkeeper: false,
    isAdded: false,
    fromOf: '',
    storeManager: false,
    fromUserId: '',
    skuId: '',
    items:[],
    onlyWx: false,
    page: 1,
    itemIsShow: false,
    loading: true,
    itemPic: [],
    thisskuid: '',
    groups: [
      { text: '分享给微信好友', value: 1, type: 'share'},
      { text: '生成海报', value: 2 },
    ],
    userInfo: app.globalData.userInfo,
    loaded: false,
    more: true
  },
  onShareAppMessage: function (res) {
    console.log(res)
    let title = app.globalData.userInfo.nickname + '分享给你一个超值特价商品，快来看看吧'
    let imageUrl = this.data.imgSrcSmall
    let fromOf = ''
    if (app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    let path = 'pages/itemdetail/itemdetail?userId=' + app.globalData.userId + '&sku=' + this.data.skuId + fromOf
    if (res.from === 'button') {
      console.log(path)
    }
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function (res) {
    if (res){
      console.log(res)
      if (res.fromOf !== undefined) {
        this.setData({
          fromOf: res.fO
        })
        console.log(this.data.fromOf)
      }
      if (res.userId !== undefined) {
        this.setData({
          fromUserId:res.userId
        })
      }
      if (res.sku !== undefined) {
        this.setData({
          skuId: res.sku
        })
        console.log(this.data.skuId)
      }
    }
    if(app.globalData.sessionId !== undefined){
      this.setData({
        logined: true
      })
    }else{
      this.setData({
        logined: false
      })
    }
    this.setData({
      userInfo: app.globalData.userInfo
    })
    this.getitemInfo()
    // console.log(app.globalData.item)
    if (res && this.data.fromOf == 'fod'){
      this.setData({
        fromOrdinary: true
      })
    } else if (res && this.data.fromOf == 'fsk'){
      this.setData({
        fromShopkeeper: true
      })
    }else{
      this.getShopkeeperInfo()
    }
    
    if (app.globalData.fromshare){
      console.log('fromshare')
      this.setData({
        detailedtc: true
      });
    } else if (app.globalData.fromapp){
      console.log('fromapp')
      var path = '/pages/product/product?wareId=' + app.globalData.item.skuId + '&spreadUrl=' + app.globalData.item.link + '&customerinfo=' + this.data.customerinfo
      console.log(path)
      this.setData({
        fromapp: true,
        item: app.globalData.item,
        path: path
      });
    } else{
      console.log('no')
    }
    this.setData({
      shareEnable: app.globalData.shareEnable
    });
    console.log(app.globalData.isdetail)
    if (app.globalData.isdetail){
      this.setData({
        detailedtc: app.globalData.isdetail
      });
    }
    
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
  },
  onShow: function (e) {
    var that = this;
    this.loginModal = this.selectComponent("#loginModal");
    this.setData({
      userInfo: app.globalData.userInfo
    })
    console.log(this.data.userInfo)
    wx.hideHomeButton()
  },
  getitemstatus(){
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: this.data.skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/user/activity/checkFreeInfo",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data.data)
        if(data.data.code == 0){
          var inviteNum
          if (data.data.data.inviteNum > 0 && data.data.data.users.length > 0){
            that.setData({
              friends: data.data.data.users
            });
          }
          if (data.data.data.inviteNum > 3){
            inviteNum = 3
          }else{
            inviteNum = data.data.data.inviteNum
          }
          if (data.data.data.isFree && data.data.data.orderId != null){
            that.setData({
              totalSecond: data.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 100,
            });
            wx.showToast({
              title: '免单成功',
              icon: 'success',
              duration: 2000
            })
          } else if (data.data.data.isBuy){
            that.setData({
              totalSecond: data.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 50
            });
          } else{
            that.setData({
              totalSecond: data.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 26
            });
          }
          
          console.log(that.data.totalSecond)
          that.countDown()
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getfreeinfo(){
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: this.data.skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (data.data.data.freeId){
          that.setData({
            freeId: data.data.data.freeId
          });
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  staractive(){
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        freeId: that.data.freeId
      },
      url: app.globalData.url + "/app/user/activity/getFreeInfo",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        that.setData({
          totalSecond: data.data.data.remainSec
        });
        console.log(that.data.totalSecond)
        that.countDown()
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  countDown(){
    var totalSecond = this.data.totalSecond
    var interval = setInterval(function () {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        wx.showToast({
          title: '活动已结束',
        });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  },
  closedtc() {
    this.setData({
      detailedtc: false
    });
  },
  homelink(){
    wx.redirectTo({
      url: '/pages/itemlist/itemlist?active=true'
    })
  },
  getclipboarddata(content) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        content: content
      },
      url: app.globalData.url + "/app/v2/goods/clipboardSpirit",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.hideLoading()
        console.log(data)
        if (data.data.code == 0) {
          if (data.data.data.isFind) {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: true
            });
          } else {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: false
            });
          }
          console.log(that.data.cbitem)
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getitemlink() {
    const that = this
    if(app.globalData.sessionId){
      that.linkData(1)
    }else{
      console.log('未登录')
      this.loginTip()
    }
    
  },
  async linkData(e){
    if(e == 2){
      console.log(2)
      await app.login(app.globalData.thisshareTicket)
      // await this.link()
    }else{
      console.log(1)
      this.link()
    }
    
  },
  async link(){
    const that = this
    var couponId
    if (this.data.item.coupons) {
      couponId = this.data.item.coupons[0].couponId
    } else {
      couponId = ''
    }
    common.post({
      url: '/app/goods/getLink',
      data: {
        skuId: this.data.skuId,
        couponId: couponId,
        sessionId: app.globalData.sessionId,
        pUserId: this.data.fromUserId
      }
    })
    .then((res) => {
      if (res.data.code == 0) {
        that.setData({
          link: res.data.link,
          logined: true
        });
        var link = encodeURIComponent(that.data.link)
        var path = '/pages/product/product?wareId=' + that.data.item.sku + '&spreadUrl=' + link + '&customerinfo=' + that.data.customerinfo
        console.log(path)
        that.setData({
          item: app.globalData.item,
          path: path
        });
      } else {
        app.login()
      }
    }).catch((res) => {
      console.log(res)
    })
  },
  videoplay(){
    this.setData({
      playvideo: true,
    });
  },
  closevp() {
    this.setData({
      playvideo: false,
    });
  },
  postformid(skuId) {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  listenerActionSheet: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden,
    })
  },
  listenerButton: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },
  formSubmit(e) {
    console.log(e)
    this.setData({
      // sharetc: true,
      actionSheetHidden: false,
      shareData: e.currentTarget.dataset.item,
      formId: e.detail.formId
    });
    console.log(this.data.shareData)
  },
  closestc() {
    this.setData({
      sharetc: false,
      shareData: []
    });
  },
  closertc() {
    this.setData({
      sharereadytc: false,
    });
  },
  closesptc() {
    this.setData({
      sharepictc: false,
      shareimg: ''
    });
  },
  saveimg() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareimg,
      success(res) {
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  shareweixinquan(e) {
    // var that = this
    // var edata = e.currentTarget.dataset.item
    // this.postformid(e.currentTarget.dataset.item.skuId)
    // wx.setStorage({
    //   key: "share",
    //   data: "true"
    // })
    // wx.showToast({
    //   title: '生成中...',
    //   icon: 'loading',
    //   duration: 2000
    // });
    // console.log(e)
    // var imgbgsrc
    // if (edata.is99) {
    //   imgbgsrc = '/img/picbg3.jpg'
    // } else {
    //   imgbgsrc = '/img/picbg.jpg'
    // }
    // console.log(imgbgsrc)
    // function sharepic(data, link) {
    //   console.log(data)
    //   if (data.data.code == 0) {
    //     var str = edata.title;
    //     str = str.slice(0, 30)
    //     var str1 = str.slice(0, 16)
    //     var str2 = str.slice(17, 30) + '...'
    //     var format = function (value) {
    //       var html, _val;
    //       value = Number(value).toFixed(2);
    //       if (value == 0) {
    //         value = 0;
    //         return html = "<text>0</text>";
    //       } else {
    //         value = Number(value).toFixed(2);
    //       }
    //       _val = value.split('.');
    //       return html = _val[0] + '.' + _val[1];
    //     }
    //     var price1 = format(edata.price)
    //     if (edata.coupons) {
    //       var price2 = format(edata.price - edata.coupons[0].discount)
    //       var reduce = '券后立省' + edata.coupons[0].discount + '元'
    //     } else {
    //       var price2 = format(edata.price)
    //       var reduce = '券后立省' + 0 + '元'
    //     }
    //     wx.getImageInfo({
    //       src: edata.image,
    //       success: function (res) {
    //         console.log(res)
    //         const sharepic = wx.createCanvasContext('myCanvas')
    //         var itemimg = res.path
    //         wx.getImageInfo({
    //           src: link,
    //           success: function (res) {
    //             console.log(res)
    //             var dcode = res.path
    //             sharepic.drawImage(imgbgsrc, 0, 0, 1080, 1920)
    //             sharepic.setFontSize(46)
    //             sharepic.setTextAlign('center')
    //             sharepic.setFillStyle('#404142')
    //             sharepic.fillText(str1, 540, 1013)
    //             sharepic.fillText(str2, 540, 1083)
    //             if (edata.tags.length > 0) {
    //               sharepic.rect(462, 1137, 164, 54)
    //               sharepic.setFillStyle('#ff4564')
    //               sharepic.fill()
    //               sharepic.setFontSize(35)
    //               sharepic.setTextAlign('center')
    //               sharepic.setFillStyle('white')
    //               sharepic.fillText(edata.tags, 544, 1178)
    //             }
    //             sharepic.setFontSize(60)
    //             sharepic.setTextAlign('center')
    //             sharepic.setFillStyle('#aaabad')
    //             sharepic.fillText(price1, 335, 1376)
    //             sharepic.setFillStyle('#ff4564')
    //             sharepic.fillText(price2, 750, 1376)
    //             sharepic.setFontSize(46)
    //             sharepic.fillText(reduce, 540, 1486)
    //             sharepic.drawImage(itemimg, 297, 454, 486, 486)
    //             if (edata.is99) {
    //               sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
    //             }
    //             sharepic.drawImage(dcode, 808, 1646, 236, 236)
    //             setTimeout(function () {
    //               sharepic.draw()
    //             }, 100)
    //             setTimeout(function () {
    //               wx.canvasToTempFilePath({
    //                 x: 0,
    //                 y: 0,
    //                 width: 1080,
    //                 height: 1920,
    //                 destWidth: 1080,
    //                 destHeight: 1920,
    //                 canvasId: 'myCanvas',
    //                 success: function (res) {
    //                   console.log(res.tempFilePath)
    //                   // wx.previewImage({
    //                   //   current: res.tempFilePath,
    //                   //   urls: [res.tempFilePath]
    //                   // })
    //                   that.setData({
    //                     sharepictc: true,
    //                     shareimg: res.tempFilePath,
    //                     sharetc: false
    //                   });

    //                 }
    //               })
    //             }, 1000)
    //           }
    //         })
    //       }
    //     })
    //   } else {
    //     wx.redirectTo({
    //       url: '/pages/index/index'
    //     })
    //   }
    // }
    // var scene = '?userid=' + getApp().globalData.userId + '&skuid=' + e.currentTarget.dataset.item.skuId
    // console.log(scene)
    // const requestTask = wx.request({
    //   method: "POST",
    //   header: { "content-type": "application/x-www-form-urlencoded" },
    //   data: {
    //     scene: scene,
    //     page: 'pages/index/index',
    //     sessionId: app.globalData.sessionId,
    //     width: '236',
    //     auto_color: 'false',
    //     line_color: '{"r":"0","g":"0","b":"0"}',
    //     is_hyaline: 'false'
    //   },
    //   url: app.globalData.url + "/wxa/qrcode/getUnlimitQrcode",
    //   async: true,
    //   timeout: 10000,
    //   success: function (data) {
    //     console.log(data.data.qrcodeLink)
    //     sharepic(data, data.data.qrcodeLink)
    //   },
    //   error: function (textStatus) {
    //     console.error(textStatus);
    //   },
    //   complete: function (XMLHttpRequest, status) {
    //     if (status == 'timeout') {
    //       requestTask.abort()    // 超时后中断请求
    //       wx.showModal({
    //         title: '提示',
    //         content: '网络超时，请重试',
    //         showCancel: 'false',
    //         success: function (res) {
    //           if (res.confirm) {
    //             wx.redirectTo({
    //               url: '/pages/index/index'
    //             })
    //           }
    //         }
    //       })
    //     }
    //   }
    // })
    wx.navigateTo({
      url: '/pages/shareimage/shareimage'
    })
  },
  favitem(e) {
    var that = this
    console.log(e)
    var edata = e.currentTarget.dataset;
    var i = edata.index
    console.log(edata)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: { skuId: edata.skuid, sessionId: app.globalData.sessionId },
      url: app.globalData.url + "/app/user/collect",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (edata.iscollect) {
          wx.showToast({
            title: '取消收藏',
            icon: "success"
          })
          var currId = edata.skuid;
          var array = that.data.item;
          array.isCollect = false;
          array.collectTotal = array.collectTotal - 1;
          that.setData({
            item: array
          });
          return false
        } else {
          wx.showToast({
            title: '收藏成功',
            icon: "success"
          })
          var currId = edata.skuid;
          var array = that.data.item;
          array.isCollect = true;
          array.collectTotal = array.collectTotal + 1;
          that.setData({
            item: array
          });
          return false
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  back: function () {
    app.globalData.item = ''
    console.log(app.globalData.isdetail)
    if (app.globalData.isdetail && typeof (app.globalData.isdetail) !== "undefined"){
      app.globalData.isdetail = false
      wx.redirectTo({
        url: '/pages/itemlist/itemlist'
      })
    }else{
      wx.navigateBack()
    }
  },
  buybtnlink: function() {
    console.log(app.globalData.sessionId)
    if (app.globalData.sessionId){
      wx.navigateToMiniProgram({
        appId: this.data.linkAppid,
        path: this.data.path,
        extraData: {
          foo: 'bar'
        },
        success(res) {
          // 打开成功
        }
      })
    }else{
      this.loginTip()
    }
    
  },
  toUsercenter(){
    wx.switchTab({
      url: '/pages/usercenter/usercenter',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toUsercenter')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toIndex(){
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  jlshare(){
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: that.data.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getShopkeeperInfo(){
    const that = this
    common.post({
      url: '/app/user/myShop', data: { sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          console.log(res.data.data.status)
          if (res.data.data.status == 2) {
            that.setData({
              isShopkeeper: true
            })

          }
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  favShop(){
    const that = this
    common.post({
      url: '/app/v2/shop/addProduct', data: { sessionId: app.globalData.sessionId, skuId: this.data.skuId}
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '已加入店铺',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            shopHas: true
          })
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getitemInfo(){
    const that = this
    wx.showLoading({
      title: '加载中',
    })
    common.post({
      url: '/app/goods/getSkuInfoBySkuId', data: { sessionId: app.globalData.sessionId, skuId: this.data.skuId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          if (res.data.sku.images){
            var imgstr = JSON.parse(res.data.sku.images)
            console.log(imgstr)
          }
          that.setData({
            item: res.data.sku,
            shopHas: res.data.sku.shopHas,
            titletxt: res.data.sku.title,
            itemPic: imgstr,
            thisskuid: res.data.sku.skuId,
          })
          setTimeout(function () {
            that.setData({
              loaded: true
            })
            wx.hideLoading()
          }, 300)
          app.globalData.item = res.data.sku
          console.log(app.globalData.item)
          wx.setNavigationBarTitle({
            title: res.data.sku.title
          })
          if(app.globalData.sessionId !== undefined){
            that.getitemlink()
          }
          that.getItemsList(res.data.sku.categoryId)
        } else if (res.data.code == -1){
          wx.showModal({
            title: '提示',
            content: '商品不存在',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
        } else if (res.data.code == -2){
          wx.showModal({
            title: '提示',
            content: '商品已过期',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.navigateBack()
              }
            }
          })
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  toStore(){
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getItemsList(categoryId){
    const that = this
    common.post({
      url: '/app/v2/goods/list', data: { categoryId: categoryId, onlyWx: this.data.onlyWx, pageNo: 1,sessionId:app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          items: res.data.data,
          itemIsShow: true
        });
      }).catch((res) => {
        console.log(res)
      })
  },
  getItemsListPage(categoryId) {
    const that = this;
    var page = that.data.page + 1;
    common.post({ url: '/app/v2/goods/list', data: { categoryId: categoryId, onlyWx: this.data.onlyWx, pageNo: page,sessionId:app.globalData.sessionId } })
      .then((res) => {
        var data = that.data.items;
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            page: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            console.log(data)
          }
          // that.setData({
          //   items: data,
          // })
          setTimeout(function () {
            that.setData({
              items: data,
              more: true
            });
            console.log(data)
          }, 300)
        } else {
          console.log('没有了')
          that.setData({
            loading: false
          });
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  buybtn(e) {
    // if (e.currentTarget.dataset.item.is99) {
    //   wx.navigateTo({
    //     url: '/pages/activeitemdetail/activeitemdetail?sku=' + e.currentTarget.dataset.item.skuId
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId
    //   })
    // }
    wx.navigateTo({
      url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId
    })
  },
  onReachBottom() {
    if (this.data.more) {
      this.setData({
        more: false
      })
      this.getItemsListPage(this.data.item.categoryId)
    }
  },
  toMyStone() {
    wx.switchTab({
      url: '/pages/myStore/myStore',
      success: function (res) {
        console.log('toMyStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  showShare(e){
    console.log(e)
    if(app.globalData.sessionId){
      // this.setData({
      //   // sharetc: true,
      //   actionSheetHidden: false,
      //   shareData: e.currentTarget.dataset.item,
      //   formId: e.detail.formId
      // });
      // console.log(this.data.shareData)
      this.canvas()
    }else{
      this.loginTip()
    }
    
  },
  // 选择画布
  canvas(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render(canvas, ctx);
    }).exec()
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode(ctx,canvas).then(function(){
              console.log('第五步完成')
              that.drawCashbackinfo(ctx,canvas).then(function(){
                console.log('第六步完成')
                that.drawCanvas(canvas)
                that.canvas1()
              })
            })
          })
        })
      })
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawCanvas2(canvas)
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    const that = this
    
    let item = this.data.item,
        txt1 = '抢券价 ￥',
        priceNew = '',
        txt2 = '京东价',
        priceOld = '¥' + item.price
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 16, 385);
        let txt1width = ctx.measureText(txt1).width + 16
        ctx.font = "bold 50px PingFangSC-Semibold";
        ctx.fillText(priceNew, txt1width, 385);
        let priceNewWidth = ctx.measureText(priceNew).width + txt1width + 20
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillText(txt2, priceNewWidth, 385);
        let txt2width = ctx.measureText(txt2).width + priceNewWidth
        ctx.fillText(priceOld, txt2width, 385);
        let priceOldWidth = ctx.measureText(priceOld).width
        ctx.beginPath()
        ctx.strokeStyle = '#fff'
        ctx.moveTo(txt2width, 376)
        ctx.lineTo(txt2width + priceOldWidth, 376)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 绘制商品标签
  drawSmalltag(ctx,canvas){
    const that = this
    let item = this.data.item
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制内容
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    let item = this.data.item,
        itemName = item.title,
        str1 = row1size(itemName),
        str2 = row2size(itemName),
        priceNew = '',
        priceOld = format(item.price),
        priceNewTxt = '抢券价',
        priceOldTxt = '京东价'
        // txt1 = solitaire.partnerCount + '人参与了群接龙567'
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.fillText(priceNewTxt, 303, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceNew, 303, 1058);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#505050";
        ctx.fillText(priceOldTxt, 530, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceOld, 530, 1058);
        let lineWidth = ctx.measureText(priceOld).width
        console.log('线长度',lineWidth)
        ctx.beginPath()
        ctx.strokeStyle = '#D6D6D6'
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1008)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1044)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.strokeStyle = '#505050'
        ctx.lineWidth = 2;
        let lineX1 = 530 - lineWidth/2,
            lineX2 = 530 + lineWidth/2
        ctx.moveTo(lineX1, 1040)
        ctx.lineTo(lineX2, 1040)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  drawCashbackinfo(ctx,canvas){
    let item = this.data.item
    let txt = '下单再返' + item.estimatePoint + '元'
    let x = 64,y = 1136, r = 12, w = 700, h = 80
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        ctx.save()
        ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.fillStyle = "#FDF7F1";
        ctx.fill()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.restore();
        ctx.textAlign = 'center';
        ctx.fillStyle = "#FF5555";
        ctx.font = "32px PingFangSC-Medium";
        ctx.fillText(txt, 414, 1190);
        console.log('img loaded')
        ctx.drawImage(img, 380, 1100, 72, 52);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/red.png'
      
      
    })
  },
  // 绘制商品图
  drawItemPic(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        ctx.beginPath()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.item.image
    })
  },
  // 绘制标签
  drawItemTag(ctx,canvas){
    const that = this
    let item = this.data.item
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + ' 分享给你一个超值商品',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    if(app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&sku=' + that.data.item.skuId + fromOf
      console.log(scene.length)
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/itemdetail/itemdetail',
          page: 'pages/itemdetail/itemdetail',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true
          })
          wx.hideLoading()
        }
      })
    })
  },
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
  loginTip(){
    this.loginModal.showPopup();
  }
})
